package com.wwz;

import com.wwz.config.FastDFSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wwz
 */
@RequestMapping("/api")
@Controller
public class FastUploadController {
    @Autowired
    private FastDFSClient fastDFSClient;
    @ResponseBody
    @RequestMapping(value = "uploadFile",method = RequestMethod.POST)
    public Map<String, Object> uploadFile(@RequestParam("uploadFile") MultipartFile filedata)
    {
        Map<String, Object> m = new HashMap<String, Object>();

        if (filedata != null && !filedata.isEmpty())
        {
            try{

                String path = fastDFSClient.uploadFile(filedata.getBytes(), filedata.getOriginalFilename());

                m.put("code","");
                m.put("url", path);
                m.put("msg", "上传成功");

            }
            catch (Exception e) {
                e.printStackTrace();
                m.put("code", "");
                m.put("msg", "上传失败");
            }
        }
        else
        {
            m.put("code", "");
            m.put("msg", "参数丢失");
        }
        return m;
    }

    @RequestMapping("downLoad")
    public ResponseEntity<byte[]> downloadPromisePdf(String fileId) {
        String fileName = "企业诚信守法承诺书.pdf";
        try {
            byte[] pdf =  fastDFSClient.downloadFile(fileId);//byte文件
            String dfileName = new String(fileName.getBytes("gb2312"), "iso8859-1");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", dfileName);
            return new ResponseEntity<>(pdf, headers, HttpStatus.OK);

        }catch (Exception e) {

        }

        return null;
    }

    public void downloadFile(String fileId){

        fastDFSClient.downloadFile(fileId);
    }
    @RequestMapping("html")
    public String toHtml(){
        return "upload";
    }
}
